/* Sends an Instant Message to all customers (same message) in the list
 * (T.S/T.B, D.D/D.D)
 * Hope you guys like the revisions! it runs uber fast!!
 */

integer amount; //amount of notecard lines    
integer line; //line number
integer loading; //test to make sure not loading
integer message_listen; //the listen to remove
integer channel_dialog; //channel for dialog
key amount_key; //amount of notecard lines (key)
key data_key; //key of the UUIDs
key http_locate_key; //key for the check function
key http_remove_key; //key for the remove function
key http_register_key; //key for the register function
key name_key; // key of the name request
key user; //the user touching
list people; //the list of ppl
list method = [HTTP_METHOD,"POST",HTTP_MIMETYPE,"application/x-www-form-urlencoded"]; //http method
list names; //the names of ppl
string first; //first name
string IM; //the message
string last; //last name
string notecard; //the notecard name
string webpage = "http://mudhoneydesign.com/goat/linden/index.php?";

GroupInstantMessage(list recipients, string message){
    integer thread = 0;
    integer x; 
    for(x = 0; x < llGetListLength(recipients); x++){
        if(thread > 10) thread = 0;
        llMessageLinked(LINK_THIS, thread, message, llList2Key(recipients, x)); //10 threads :D
        llOwnerSay("Instant Message sent to: " + llList2String(names, x)); //tell the owner that the request has been sent
        thread++;
    }
}

default{
    state_entry(){
        /* Channels below */
        channel_dialog = ( -1 * (integer)("0x" + llGetSubString((string)llGetKey(), -5, -1)));
        
        notecard = llGetInventoryName(INVENTORY_NOTECARD, 0);

        loading = TRUE; //set to loading
        llOwnerSay("loading, please wait ..."); //tell em.
        amount_key = llGetNumberOfNotecardLines(notecard); //get the amount of lines
    }

    dataserver(key requested, string data){ //was revamped, now uses less variables, and requires a key only.
        if(requested == amount_key){
            amount = (integer) data;
            
            data_key = llGetNotecardLine(notecard, line++); //start loading from notecard
        }

        else if(requested == data_key){
            if(data != EOF){ //if its not the end of file
                if(llGetSubString(data, 0, 1) != "//") people += llStringTrim(data, STRING_TRIM); //record the data if its not commented
                else amount -= 1; //gives a more accurate reading of all lines
                float done = ((float)line / (float)amount) * 100;
                llSetText("Loading Notecard: " + notecard +" " + (string)done + "% loaded from notecard....", <1, 0, 1>, 1);
                data_key = llGetNotecardLine(notecard, line++); //continue loading
            }

            else{    //if its the end of the file.
                llOwnerSay("Finished loading"); //tell em
                line = 0; //reset line count
                amount = llGetListLength(people); //from now on, no more issues with loading, and having blank lines :D
                llOwnerSay("Loading names...");
                name_key = llRequestAgentData(llList2Key(people, line++), DATA_NAME); //start requesting names

            }
        }
        
        else if(requested == name_key){ //if a name is returned
            if(line < amount + 1){ // if the data is still coming
                float done = ((float)line - 1  / (float)amount) * 100; //percent done;
                llSetText("Loading Names... " + (string)done + "% loaded from server...", <1, 0, 1>, 1);
                names += data;
                
                name_key = llRequestAgentData(llList2Key(people, line++), DATA_NAME);
                if(llGetListLength(names) == amount){
                    llOwnerSay("Done loading, Touch prim to send messages");
                    llSetText("Touch to send messages", <1, 0, 1>, 1); //set the text
                    loading = FALSE; //its done loading
                    line = 0; //set line back to 0
                }
            }
        }
    }

    listen(integer channel, string name, key id, string message){
        if(channel == 5){
            llListenRemove(message_listen); //always be polite, remove the listen :D
            llSetText("Sending messages...", <1, 0, 1>, 1);
            loading = TRUE; //set it to sending so they can't do anything

            IM = message; //set what they say to the mesage

            GroupInstantMessage(people, IM); //start the function
            llSetText("Touch to send messages", <1, 0, 1>, 1); //change it from sending messsages.... to this
            loading = FALSE; //set it to not sending
            llOwnerSay("Done Sending! Touch prim to send messages"); //done
        }
        
        else{ //if it isnt on channel 5, its a user trying to add / remove themself
            if(message == "Accept"){
                string body = "do=register&uuid=" + llEscapeURL((string)user) + "&first=" + first + "&last=" + last;
                            
                http_register_key = llHTTPRequest(webpage, method, body);
            }

            else{ //obviously they are removing...
                string first = llEscapeURL(llGetSubString(llDetectedName(0),0, (llSubStringIndex(llDetectedName(0), " ") - 1))); //first name
                string last = llEscapeURL(llGetSubString(llDetectedName(0), (llSubStringIndex(llDetectedName(0), " ") + 1), llStringLength(llDetectedName(0)))); //last name
                string body = "do=remove&uuid=" + llEscapeURL((string)user) + "&first=" + first + "&last=" + last;
                            
                http_remove_key = llHTTPRequest(webpage, method, body);
            }
        }
    }
    
        
    timer(){ //if it times out...
        llListenRemove(message_listen); //I CANT WAIT ALL DAY!!!
        llSetTimerEvent(0); //make it so it dun loop!
    }

    touch_start(integer total_number){
        if (llDetectedKey(0) == llGetOwner()){
            if(!loading){ //if its not loading...
                message_listen = llListen(5, "", llGetOwner(), ""); //listen for the owner..
                llOwnerSay("Please say the message you would like to send to everyone on channel 5 (will time out in 60 seconds)"); //tell em to say the message!
                llSetTimerEvent(60);
            }
            
            else llOwnerSay("Please wait, script busy!"); //if its in the process, tell em to wait.
        }
        else{ //strictly beta
            if(!loading){
                first = llEscapeURL(llGetSubString(llDetectedName(0),0, (llSubStringIndex(llDetectedName(0), " ") - 1))); //first name
                last = llEscapeURL(llGetSubString(llDetectedName(0), (llSubStringIndex(llDetectedName(0), " ") + 1), llStringLength(llDetectedName(0)))); //last name

                user = llDetectedKey(0);

                string body = "do=locate&uuid=" + llEscapeURL((string)user); //the body of the HTML :D
            
                http_locate_key = llHTTPRequest(webpage, method, body); //the http query
            }
            
            else llOwnerSay("Please wait, script busy!"); //if its in the process, tell em to wait.
        }
    }

    http_response(key request_id, integer status, list metadeta, string body){
        if(request_id == http_locate_key){ //if the query was to check the database
            if(body == "key_found"){ //if it found the key
                message_listen = llListen(channel_dialog, "", user, "Yes"); //only listens for a yes. otherwise it doesn't need to do anything!
                llDialog(user, "Would you like to be removed from this group? (menu will time out in 60 seconds)", ["Yes", "No"], channel_dialog);
                llSetTimerEvent(60); //obviously always be polite :D
            }
            
            else if(body == "key_not_found"){//if it found no key
                message_listen = llListen(channel_dialog, "", user, "Agree"); //only listens for a yes, otherwise it doesn't need to do anything!
                llDialog(user, "By pressing agree, you agree to receive information, and/or items from MudHoney Designs. (menu will time out in 60 seconds)", ["Agree", "Disagree"], channel_dialog);
                llSetTimerEvent(60); //obviously always be polite :D
            }

            else{ // if anything else happens (like it times out, or no response)
                llInstantMessage(user, "An unexpected error has ocurred, please try again later.");
            }
        }

        else if(request_id == http_register_key){
            if(body == "new_key_added"){
                people += user; //add them to the internal uuid list
                names += first + " " + last; //add them to the internal name list
                
                llInstantMessage(user, "You have been successfully added!");
            }

            else{ // if anything else happens (like it times out, or no response)
                llInstantMessage(user, "An unexpected error has ocurred, please try again later.");
            }
        }
        
        else if(request_id == http_remove_key){
            if(body == "key_removed"){
                integer key_index = llListFindList(people, ["user"]);
                integer name_index = llListFindList(names, [first + " " + last]);

                people = llDeleteSubList(people, key_index, key_index);
                names = llDeleteSubList(names, name_index, name_index);

                llInstantMessage(user, "You have been successfully removed!");
            }
        }
    }
}

//stuff to work with
//switch ($DO) {
//    case "delete" :
//        $result = $Customer1->customerRemove();
//        echo $result;
//        break;
//    case "register" :
//        $result = $Customer1->customerRegister();
//        echo $result;
//        break;
//    case "list" :
//        $result = $Customer1->displayUserListPlainText();
//        break;
//    case "locate" :
//       $result = $Customer1->checkUserExistance();
//        break;
//    default :
//        echo "missing_operator";
//        break;
//}